package com.jz.community.moduleshopping.orderList.adapter;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.jz.community.basecomm.bean.BaseResponseInfo;
import com.jz.community.basecomm.constant.AppConstants;
import com.jz.community.basecomm.constant.ConstantErrorCode;
import com.jz.community.basecomm.utils.BaseImageLoaderUtils;
import com.jz.community.basecomm.utils.CharacterUtils;
import com.jz.community.basecomm.utils.ConverterUtils;
import com.jz.community.basecomm.utils.DialogUtils;
import com.jz.community.basecomm.utils.Preconditions;
import com.jz.community.basecomm.utils.RxTextTool;
import com.jz.community.basecomm.utils.SHelper;
import com.jz.community.basecomm.utils.WpToast;
import com.jz.community.moduleshopping.R;
import com.jz.community.moduleshopping.confirmOrder.bean.SubmitOrderResultBean;
import com.jz.community.moduleshopping.confirmOrder.enums.OrderPayFormType;
import com.jz.community.moduleshopping.confirmOrder.payPop.NewCommPayPopUp;
import com.jz.community.moduleshopping.orderDetail.task.OrderDeleteTask;
import com.jz.community.moduleshopping.orderDetail.ui.OrderDetailActivity;
import com.jz.community.moduleshopping.orderDetail.ui.OrderEvaluateActivity;
import com.jz.community.moduleshopping.orderList.bean.NewOrderListInfo;
import com.jz.community.moduleshopping.orderList.bean.SpecialCouponBean;
import com.jz.community.moduleshopping.orderList.enums.OrderStatusType;
import com.jz.community.moduleshopping.orderList.task.ConfirmOrderStatusTask;
import com.jz.community.moduleshopping.orderList.task.SpecialCouponForOrderTask;
import com.jz.community.moduleshopping.orderList.view.NotSnatchDialog;
import com.jz.community.moduleshopping.orderList.view.ReceivingGoodsDialog;
import com.jz.community.moduleshopping.orderList.view.SpecialCouponDialog;

import java.util.List;

/**
 * Created by Tony.Fan on 2018/4/27 10:18
 * 订单列表
 */
public class NewOrderListAdapter extends BaseQuickAdapter<NewOrderListInfo.EmbeddedBean.OrderInfoesBean, BaseViewHolder> {
    private ImageView img_finish;
    private TextView status_tv;
    private TextView btn_gray;
    private TextView btn_red;
    private NewCommPayPopUp payPopUp;
    private RecyclerView order_list_rv;
    private LinearLayout new_order_one_layout;
    private OrderMultiGoodsAdapter orderMultiGoodsAdapter;

    public NewOrderListAdapter(@Nullable List datas) {
        super(R.layout.module_shopping_item_order_list_new, datas);
    }

    @Override
    public void onBindViewHolder(BaseViewHolder holder, int position) {
        initView(holder);
        if (!Preconditions.isNullOrEmpty(getItem(position))) {
            List<NewOrderListInfo.EmbeddedBean.OrderInfoesBean.OrderItemListBean> orderItemListBeans = getItem(position).getOrderItemList();
            if (!Preconditions.isNullOrEmpty(orderItemListBeans) && orderItemListBeans.size() > 1) {
                SHelper.vis(order_list_rv);
                SHelper.gone(new_order_one_layout);
                showShopInfo(holder, position);
                handleBindOrderListAdapter(orderItemListBeans, position);
            } else {
                SHelper.vis(new_order_one_layout);
                SHelper.gone(order_list_rv);
                for (NewOrderListInfo.EmbeddedBean.OrderInfoesBean.OrderItemListBean orderItem : orderItemListBeans) {
                    handleGoodsData(holder, orderItem, position);
                }
            }
        }
        super.onBindViewHolder(holder, position);
    }

    @Override
    protected void convert(BaseViewHolder helper, NewOrderListInfo.EmbeddedBean.OrderInfoesBean item) {
    }

    private void handleBindOrderListAdapter(List<NewOrderListInfo.EmbeddedBean.OrderInfoesBean.OrderItemListBean> orderItemListBeans, int inPos) {
        LinearLayoutManager layoutManager = new LinearLayoutManager(mContext);
        layoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        order_list_rv.setLayoutManager(layoutManager);
        orderMultiGoodsAdapter = new OrderMultiGoodsAdapter(orderItemListBeans);
        order_list_rv.setAdapter(orderMultiGoodsAdapter);
        orderMultiGoodsAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                Intent intent = new Intent(mContext, OrderDetailActivity.class);
                intent.putExtra("orderId", getItem(inPos).getOrderId());
                intent.putExtra("couponMark", getItem(inPos).getCouponMark());
                mContext.startActivity(intent);
            }
        });
    }

    private void initView(BaseViewHolder holder) {
        img_finish = holder.getView(R.id.new_order_finish_img);
        status_tv = holder.getView(R.id.new_order_status);
        btn_gray = holder.getView(R.id.new_order_btn_gray);
        btn_red = holder.getView(R.id.new_order_btn_red);
        order_list_rv = holder.getView(R.id.order_list_rv);
        new_order_one_layout = holder.getView(R.id.new_order_one_layout);
    }

    /**
     * 订单商品基本信息
     *
     * @param helper
     */
    private void handleGoodsData(BaseViewHolder helper, NewOrderListInfo.EmbeddedBean.OrderInfoesBean.OrderItemListBean orderItem, int position) {
        TextView orderOneGrayPrice = helper.getView(R.id.order_one_gray_price);
        helper.setText(R.id.order_one_name, orderItem.getGoodsName());
        helper.setText(R.id.order_sku_name_tv, orderItem.getSkuName());
        helper.setText(R.id.order_one_num, "X" + orderItem.getGoodsCount());

        BaseImageLoaderUtils.getInstance().loadRamdomImage(mContext, helper.getView(R.id.order_one_img), orderItem.getGoodsImg());

        if (!Preconditions.isNullOrEmpty(orderItem.getDiscountPrice())) {
            helper.setText(R.id.order_one_price, AppConstants.MONEY + orderItem.getDiscountPrice());
            RxTextTool.getBuilder("").append(AppConstants.MONEY + CharacterUtils.roundByGoodPrice(ConverterUtils.toDouble(orderItem.getPrice()))).setStrikethrough().into(orderOneGrayPrice);
            SHelper.vis(orderOneGrayPrice);
        } else {
            helper.setText(R.id.order_one_price, AppConstants.MONEY + orderItem.getPrice());
            SHelper.gone(orderOneGrayPrice);
        }
        showShopInfo(helper, position);
    }

    /**
     * 显示店铺信息
     *
     * @param helper
     * @param position
     */
    private void showShopInfo(BaseViewHolder helper, int position) {
        if (Preconditions.isNullOrEmpty(getItem(position).getShopName())) {
            SHelper.gone(helper.getView(R.id.order_one_shop));
        } else {
            helper.setText(R.id.order_one_shop, getItem(position).getShopName());
        }
        helper.setText(R.id.new_order_time, getItem(position).getCreateDate());
        showGoodsPrice(helper, getItem(position).getRealPrice());
        handleAllOrderHideAndShow(position);
    }

    /**
     * 显示商品支付价格
     *
     * @param helper
     * @param payPrice
     */
    private void showGoodsPrice(BaseViewHolder helper, String payPrice) {

        helper.setText(R.id.new_order_pay_price_tv, "¥" + payPrice);
    }

    /**
     * 订单状态处理
     *
     * @param position
     */
    private void handleAllOrderHideAndShow(int position) {

        String orderStatus = getItem(position).getStatus();
        int couponMark = getItem(position).getCouponMark();

        if (Preconditions.isNullOrEmpty(orderStatus)) {
            return;
        }

        //待支付
        if (orderStatus.equals(OrderStatusType.ORDER_UNPAID_PAY_STATUS.getOrderStatus())) {
            handleTitleShow(R.string.payment_on_behalf);
            SHelper.gone(btn_gray, img_finish);
            SHelper.vis(btn_red);
            handleBtnRedShow(R.string.immediately_pay);
            addListener(btn_red, btn_gray, position, OrderStatusType.ORDER_UNPAID_PAY_STATUS.getOrderStatus());
            //待发货
        } else if (orderStatus.equals(OrderStatusType.ORDER_ALREADY_PAY_STATUS.getOrderStatus()) || orderStatus.equals(OrderStatusType.ORDER_RECEIPT_STATUS.getOrderStatus()) || orderStatus.equals(OrderStatusType.ORDER_DELIVERY_STATUS.getOrderStatus())) {
            handleWaitOrderStatus(orderStatus, position);
            //待收货
        } else if (orderStatus.equals(OrderStatusType.ORDER_SHIPPED_STATUS.getOrderStatus())) {
            handleTitleShow(R.string.wait_take_goods);
            SHelper.gone(img_finish, btn_gray);
            SHelper.vis(btn_red);
            if (couponMark == 0) {
                handleBtnRedShow(R.string.confirm_the_goods);
            } else {
                handleBtnRedShow(R.string.confirm_the_goods_coupon);
            }
            addListener(btn_red, btn_gray, position, OrderStatusType.ORDER_SHIPPED_STATUS.getOrderStatus());
            //交易成功(已收货,待评价)
        } else if (orderStatus.equals(OrderStatusType.ORDER_SUCCESS_STATUS.getOrderStatus())) {
            handleTitleShow(R.string.transaction_completion);
            SHelper.vis(btn_red);
            SHelper.gone(img_finish, btn_gray);
            handleBtnRedShow(R.string.evaluate);
            addListener(btn_red, btn_gray, position, OrderStatusType.ORDER_SUCCESS_STATUS.getOrderStatus());
            //交易成功(已评价)
        } else if (orderStatus.equals(OrderStatusType.ORDER_SUCCESS_EVALUATED_STATUS.getOrderStatus())) {
            SHelper.vis(img_finish);
            handleTitleShow(R.string.transaction_completion);
            SHelper.gone(btn_gray);
            SHelper.vis(btn_red);
            handleBtnRedShow(R.string.delete_order);
            addListener(btn_red, btn_gray, position, OrderStatusType.ORDER_SUCCESS_EVALUATED_STATUS.getOrderStatus());
            //商家取消 | 用户取消 | 长时间未支付 | 自动取消
        } else if (orderStatus.equals(OrderStatusType.ORDER_USER_CLOSE_STATUS.getOrderStatus()) ||
                orderStatus.equals(OrderStatusType.ORDER_MERCHANT_CLOSE_STATUS.getOrderStatus()) ||
                orderStatus.equals(OrderStatusType.ORDER_SYSTEM_CLOSE_STATUS.getOrderStatus()) ||
                orderStatus.equals(OrderStatusType.ORDER_MERCHANT_REFUSAL_CLOSE_STATUS.getOrderStatus())) {
            handleTitleShow(R.string.cancel_and_refund);
            SHelper.gone(img_finish, btn_gray);
            SHelper.vis(btn_red);
            handleBtnRedShow(R.string.delete_order);
            addListener(btn_red, btn_gray, position, getItem(position).getStatus());
        } else {
            status_tv.setText(getItem(position).getStatusDsc());
        }
    }

    private void handleTitleShow(int showTitle) {
        status_tv.setText(showTitle);
    }

    private void handleBtnRedShow(int showRedBtn) {
        btn_red.setText(showRedBtn);
    }

    private void handleBtnGrayShow(int showGrayBtn) {
        btn_gray.setText(showGrayBtn);
    }

    /**
     * 处理待收货订单状态
     *
     * @param orderStatus
     */
    private void handleWaitOrderStatus(String orderStatus, int position) {
        // 已支付 未接单
        if (orderStatus.equals(OrderStatusType.ORDER_ALREADY_PAY_STATUS.getOrderStatus())) {
            handleTitleShow(R.string.pending_order);
            SHelper.gone(btn_gray, img_finish, btn_red);
            addListener(btn_red, btn_gray, position, OrderStatusType.ORDER_ALREADY_PAY_STATUS.getOrderStatus());
            //已接单,待发货
        } else if (orderStatus.equals(OrderStatusType.ORDER_RECEIPT_STATUS.getOrderStatus())) {
            handleTitleShow(R.string.pending_delivery);
            SHelper.gone(img_finish, btn_gray);
            SHelper.vis(btn_red);
            handleBtnRedShow(R.string.reminding_shipments);
            btn_red.setEnabled(true);
            addListener(btn_red, btn_gray, position, OrderStatusType.ORDER_RECEIPT_STATUS.getOrderStatus());
            //已提醒发货
        } else if (orderStatus.equals(OrderStatusType.ORDER_DELIVERY_STATUS.getOrderStatus())) {
            handleTitleShow(R.string.pending_delivery);
            SHelper.gone(img_finish, btn_gray);
            SHelper.vis(btn_red);
            handleBtnRedShow(R.string.reminding_the_shipments);
            btn_red.setEnabled(false);
        }
    }

    /**
     * 支付弹窗
     */
    private void showPayPop(View v, int position) {
        payPopUp = new NewCommPayPopUp(mContext, getItem(position).getRealPrice(), OrderPayFormType.PAY_FORM_TYPE_2.getPayFormType());
        payPopUp.setConfirmPayOrder(new SubmitOrderResultBean(getItem(position).getOrderId()));
        payPopUp.showAtLocation(v, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
    }

    /**
     * 订单状态按钮监听
     *
     * @param btnRed
     */
    private void addListener(TextView btnRed, TextView btnGray, int position, String orderStatus) {

        btnRed.setOnClickListener(v -> {
            //支付
            if (orderStatus.equals(OrderStatusType.ORDER_UNPAID_PAY_STATUS.getOrderStatus())) {
                NewOrderListAdapter.this.showPayPop(v, position);
                //确认发货
            } else if (orderStatus.equals(OrderStatusType.ORDER_SHIPPED_STATUS.getOrderStatus())) {
                if (getItem(position).getCouponMark() == 0) {
                    confirmOrderDialog(getItem(position).getOrderId(), OrderStatusType.FUNMARK_5, OrderStatusType.ORDER_SHIPPED_STATUS.getOrderStatus(), position);
                } else {
                    confirmOrderCouponDialog(getItem(position).getOrderId(), OrderStatusType.FUNMARK_5, OrderStatusType.ORDER_SHIPPED_STATUS.getOrderStatus(), position);
                }
                //交易完成评价
            } else if (orderStatus.equals(OrderStatusType.ORDER_SUCCESS_STATUS.getOrderStatus())) {
                mContext.startActivity(new Intent(mContext, OrderEvaluateActivity.class)
                        .putExtra("orderId", ConverterUtils.toString(getItem(position).getOrderId()))
                        .putExtra("shopId", getItem(position).getShopId()));
                //删除订单
            } else if (orderStatus.equals(OrderStatusType.ORDER_SUCCESS_EVALUATED_STATUS.getOrderStatus())) {
                showDeleteDialog(getItem(position).getOrderId(), position);
                //删除订单
            } else if (orderStatus.equals(OrderStatusType.ORDER_USER_CLOSE_STATUS.getOrderStatus()) ||
                    orderStatus.equals(OrderStatusType.ORDER_MERCHANT_CLOSE_STATUS.getOrderStatus()) ||
                    orderStatus.equals(OrderStatusType.ORDER_SYSTEM_CLOSE_STATUS.getOrderStatus()) ||
                    orderStatus.equals(OrderStatusType.ORDER_MERCHANT_REFUSAL_CLOSE_STATUS.getOrderStatus())) {
                showDeleteDialog(getItem(position).getOrderId(), position);
                //提醒发货
            } else if (orderStatus.equals(OrderStatusType.ORDER_RECEIPT_STATUS.getOrderStatus())) {
                updateOrderStatus(getItem(position).getOrderId(), OrderStatusType.FUNMARK_4, OrderStatusType.ORDER_RECEIPT_STATUS.getOrderStatus(), position);
            }
        });
    }

    /**
     * 更新订单状态
     *
     * @param orderId
     * @param funMark
     */
    private void updateOrderStatus(String orderId, String funMark, String orderStatus, int position) {
        new ConfirmOrderStatusTask((Activity) mContext, o -> {
            BaseResponseInfo baseResponseInfo = (BaseResponseInfo) o;
            if (Preconditions.isNullOrEmpty(baseResponseInfo)) {
                return;
            }
            if (baseResponseInfo.getCode() == ConstantErrorCode.SUCC_CODE) {
                handleUpdateOrderStatus(orderStatus, position);
                if (getItem(position).getCouponMark() != 0) {
                    //获取优惠券
                    getCoupon(orderId);
                }
            } else {
                WpToast.l(mContext, baseResponseInfo.getMessage());
            }
        }).execute(orderId, funMark, "");
    }


    private void getCoupon(String orderId) {
        new SpecialCouponForOrderTask((Activity) mContext, o -> {
            SpecialCouponBean specialCouponBean = (SpecialCouponBean) o;
            if (Preconditions.isNullOrEmpty(specialCouponBean) || Preconditions.isNullOrEmpty(specialCouponBean.get_embedded()) || Preconditions.isNullOrEmpty(specialCouponBean.get_embedded().getContent())) {
                new NotSnatchDialog(mContext).show();
                return;
            }
            SpecialCouponDialog dialog = new SpecialCouponDialog(mContext);
            dialog.setData(specialCouponBean);
            dialog.show();
        }).execute(orderId);
    }

    /**
     * 更新订单状态
     *
     * @param orderStatus
     */
    private void handleUpdateOrderStatus(String orderStatus, int position) {
        if (orderStatus.equals(OrderStatusType.ORDER_RECEIPT_STATUS.getOrderStatus())) {
            WpToast.l(mContext, "提醒发货成功");
            getItem(position).setStatus(OrderStatusType.ORDER_DELIVERY_STATUS.getOrderStatus());
            notifyDataSetChanged();
        } else if (orderStatus.equals(OrderStatusType.ORDER_SHIPPED_STATUS.getOrderStatus())) {
            WpToast.l(mContext, "确认收货成功");
            getItem(position).setStatus(OrderStatusType.ORDER_SUCCESS_STATUS.getOrderStatus());
            notifyDataSetChanged();
        }
    }

    /**
     * 确认收货弹框
     *
     * @param orderId
     * @param funMark
     * @param orderStatus
     * @param position
     */
    private void confirmOrderDialog(String orderId, String funMark, String orderStatus, int position) {
        new DialogUtils(mContext, "确认收货前，请确保你已经收到商品!").setOnDialogClickListener(new DialogUtils.OnDialogClickListener() {
            @Override
            public void onLeftClick() {
            }

            @Override
            public void onRightClick() {
                updateOrderStatus(orderId, funMark, orderStatus, position);
            }
        });
    }

    private void confirmOrderCouponDialog(String orderId, String funMark, String orderStatus, int position) {
        new ReceivingGoodsDialog(mContext, () -> updateOrderStatus(orderId, funMark, orderStatus, position)).show();
    }

    /**
     * 删除订单弹框
     */
    private void showDeleteDialog(String orderId, int position) {
        AlertDialog alertDialog = new AlertDialog.Builder(mContext)
                .setTitle(R.string.delete)
                .setMessage(R.string.is_sure_delete_order)
                .setPositiveButton(R.string.delete, (dialog, which) -> {
                    if (!Preconditions.isNullOrEmpty(orderId)) {
                        handleDeleteOrder(orderId, position);
                    }
                })
                .setNegativeButton(R.string.cancel, null).show();
        alertDialog.getButton(DialogInterface.BUTTON_POSITIVE).setTextColor(Color.RED);
        alertDialog.getButton(DialogInterface.BUTTON_NEGATIVE).setTextColor(Color.BLACK);
    }

    /**
     * 删除订单
     */
    private void handleDeleteOrder(String orderId, int position) {
        new OrderDeleteTask((Activity) mContext, o -> {
            BaseResponseInfo baseResponseInfo = (BaseResponseInfo) o;
            if (baseResponseInfo.getCode() == ConstantErrorCode.SUCC_CODE) {
                WpToast.l(mContext, "删除成功");
                NewOrderListAdapter.this.remove(position);
            } else {
                WpToast.l(mContext, "删除失败");
            }

        }).execute(orderId);
    }

}
